<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="../include/laypublic.jsp"%>
<!DOCTYPE html>
<html>
<head>
<title>投建月度管控-新增</title>
</head>
<style>
.fieldset {
	margin-top: 5px;
	margin-bottom: 0px
}

.layui-legend {
	background-color: #5fb878;
	font-size: 15px !important;
	width: 170px;
}

.layui-form-item {
	margin-bottom: 5px;
	clear: both;
	*zoom: 1;
}

.layui-form-label {
	width: 150px;
}

.right {
	float: right;
}

.width106 {
	width: 106px;
}

.width98 {
	width: 98px;
}

.width60 {
	width: 60px;
}

.width140 {
	width: 140px;
}

.width200 {
	width: 200px;
}

.margin-lt20 {
	margin-left: 20px;
}

.margin-rt20 {
	margin-right: 20px;
}
</style>
<body>
	<div class="layui-fluid">
		<div class="layui-card">
			<div class="layui-tab-item layui-show">
				<div style="padding-top: 15px;">&nbsp;</div>
				<form class="layui-form" id="addInfo_form">
					<fieldset class="layui-elem-field layui-field-title fieldset" id="baseInfo">
						<legend class="layui-btn layui-legend" style="text-align: left; cursor: default;">项目基础信息 > </legend>
						<div style="margin-top: 20px">
							<div class="layui-form-item">
								<div class="layui-inline">
									<label class="layui-form-label">申请公司</label>
									<div class="layui-input-inline">
										<input type="hidden" name="hrOrgId" value="${bindOrgId}">
										<input type="text" value="${bindOrgName}" style="border: 0px;" readonly="readonly" class="layui-input">
									</div>
								</div>
								<div class="layui-inline">
									<label class="layui-form-label">申请部门</label>
									<div class="layui-input-inline">
										<input type="hidden" name="hrDeptId" value="${bindDeptId}">
										<input type="text" value="${bindDeptName}" style="border: 0px;" readonly="readonly" class="layui-input">
									</div>
								</div>
								<div class="layui-inline">
									<label class="layui-form-label">申请人</label>
									<div class="layui-input-inline">
										<input type="hidden" name="hrStaffApplyId" value="${SESSION_KEY_USER_DETAIL.hrStaffId }">
										<input type="text" name="staffName" value="${staffName }" readonly="readonly" style="border: 0px" autocomplete="off" class="layui-input">
									</div>
								</div>
							</div>
							<div class="layui-form-item">
								<div class="layui-inline">
									<label class="layui-form-label">项目名称</label>
									<div class="layui-input-inline">
										<select name="programPlanId" id="add_select_proId" lay-verify="required" lay-filter="add_select_proId" lay-search>
											<option value="">请选择</option>
											<c:if test="${not empty programPlans }">
												<c:forEach items="${programPlans}" var="pro">
													<option value="${pro.id}">${pro.proName }</option>
												</c:forEach>
											</c:if>
										</select>
									</div>
								</div>
								<div class="layui-inline">
									<label class="layui-form-label">项目城市</label>
									<div class="layui-input-inline">
										<input type="text" id="sgCityName" name="sgCityName" style="border: 0px;" readonly="readonly" class="layui-input">
										<input type="hidden" name="sgCityId" id="sgCityId">
										<input type="hidden" name="proCode" id="proCode">
										<input type="hidden" name="proName" id="proName">
										<input type="hidden" name="types" id="types">
									</div>
								</div>
								<div class="layui-inline">
									<label class="layui-form-label">项目状态</label>
									<div class="layui-input-inline">
										<infopub:select entireName="-项目状态" name="proState" layVerify="required" type="dic" groupNo="A00010066"></infopub:select>
									</div>
								</div>
							</div>
							<div class="layui-form-item">
								<div class="layui-inline">
									<label class="layui-form-label">管控月份</label>
									<div class="layui-input-inline">
										<input type="text" id="query-input-month" name="ctrlMonthStr" lay-verify="required" readonly="readonly" class="layui-input">
									</div>
								</div>
							</div>
						</div>
					</fieldset>
					<fieldset class="layui-elem-field layui-field-title fieldset" id="loanInfo">
				  		<legend class="layui-btn layui-legend" style="text-align:left;cursor:default;">总分包付款完成率 ></legend>
					  	<div style="margin-top:20px">
					  		<div class="layui-form-item">
							    <div class="layui-inline">
							    	<label class="layui-form-label">总分包付款完成率（%）</label>
						      		<div class="layui-input-inline">
							      		<input type="text" id="packPayRateId" name="packPayRate" maxlength="10" lay-verify="required|floatNumber" autocomplete="off" class="layui-input">
						      		</div>
							    </div>
						    </div>
						    <fieldset class="layui-elem-field layui-field-title fieldset"  id="customerFile">
						  		<legend style="margin-left:40px;font-size:15px;font-weight:bold;">分包付款完成率清单 ></legend>
							  	<div style="margin-top:20px" id="subDiv">
							  	</div>
							</fieldset>
						</div>
					</fieldset>
					<fieldset class="layui-elem-field layui-field-title fieldset" id="subInfo">
						<legend class="layui-btn layui-legend" style="text-align: left; cursor: default;">里程碑节点完成情况 ></legend>
						<div style="margin-top: 20px" id ="mydiv">
						</div>
					</fieldset>
					<fieldset class="layui-elem-field layui-field-title fieldset"  id="creditInfo">
				  		<legend class="layui-btn layui-legend" style="text-align:left;cursor:default;">管控说明  ></legend>
					  	<div style="margin-top:20px">
					  		<div class="layui-form-item">
							    <div class="layui-inline">
							    	<label class="layui-form-label">延误天数（天）</label>
						      		<div class="layui-input-inline">
							      		<input name="delayDaysMax" id="delayDaysMax" style="border: 0px;" readonly="readonly" class="layui-input">
						      		</div>
							    </div>
							    <div class="layui-inline">
							    	<label class="layui-form-label">本月工程计划完成率（%）</label>
						      		<div class="layui-input-inline">
							      		<input name="monthPlanRate" id="monthPlanRate" style="border: 0px;" readonly="readonly" class="layui-input">
						      		</div>
							    </div>
							    <div class="layui-inline">
							    	<label class="layui-form-label">开累计划完成率（%）</label>
						      		<div class="layui-input-inline">
							      		<input name="sumPlanRate" id="sumPlanRate" style="border: 0px;" readonly="readonly" class="layui-input">
						      		</div>
							    </div>
						    </div>
					  		<div class="layui-form-item">
							    <div class="layui-inline">
							    	<label class="layui-form-label width200">开累计划应完成形象（选填）</label>
						      		<div class="layui-input-inline">
							      		<textarea name="sumPlanImage" maxlength="500" placeholder="请输入开累计划应完成形象" class="layui-textarea" style="width:899px;height:90px;"></textarea>
						      		</div>
							    </div>
						    </div>
					  		<div class="layui-form-item">
							    <div class="layui-inline">
							    	<label class="layui-form-label width200">实际形象进度描述（选填）</label>
						      		<div class="layui-input-inline">
							      		<textarea name="actImageShow" maxlength="500" placeholder="请输入实际形象进度描述" class="layui-textarea" style="width:899px;height:90px;"></textarea>
						      		</div>
							    </div>
						    </div>
					  		<div class="layui-form-item">
							    <div class="layui-inline">
							    	<label class="layui-form-label width200">延误原因（选填）</label>
						      		<div class="layui-input-inline">
							      		<textarea name="delayReason" maxlength="500" placeholder="请输入延误原因" class="layui-textarea" style="width:899px;height:90px;"></textarea>
						      		</div>
							    </div>
						    </div>
					  		<div class="layui-form-item">
							    <div class="layui-inline">
							    	<label class="layui-form-label width200">采取的管理动作（选填）</label>
						      		<div class="layui-input-inline">
							      		<textarea name="actionTake" maxlength="500" placeholder="请输入采取的管理动作" class="layui-textarea" style="width:899px;height:90px;"></textarea>
						      		</div>
							    </div>
						    </div>
					  		<div class="layui-form-item">
							    <div class="layui-inline">
							    	<label class="layui-form-label width200">影响进度的图纸情况（选填）</label>
						      		<div class="layui-input-inline">
							      		<textarea name="drawShow" maxlength="500" placeholder="请输入影响进度的图纸情况" class="layui-textarea" style="width:899px;height:90px;"></textarea>
						      		</div>
							    </div>
						    </div>
					  		<div class="layui-form-item">
							    <div class="layui-inline">
							    	<label class="layui-form-label width200">影响进度的招标情况（选填）</label>
						      		<div class="layui-input-inline">
							      		<textarea name="bidShow" maxlength="500" placeholder="影响进度的招标情况" class="layui-textarea" style="width:899px;height:90px;"></textarea>
						      		</div>
							    </div>
						    </div>
					  		<div class="layui-form-item">
							    <div class="layui-inline">
							    	<label class="layui-form-label width200">质量、安全（飞检、抽查、监理等发现问题整改）（选填）</label>
						      		<div class="layui-input-inline">
							      		<textarea name="qaMemo" maxlength="500" placeholder="质量、安全（飞检、抽查、监理等发现问题整改）" class="layui-textarea" style="width:899px;height:90px;"></textarea>
						      		</div>
							    </div>
						    </div>
					  	</div>
					</fieldset>
					<fieldset class="layui-elem-field layui-field-title fieldset" >
		  				<legend class="layui-btn layui-legend" style="text-align:left;cursor:default;">附件信息  ></legend>
				  		<div style="margin-top:20px;">
					  		<div class="layui-form-item">
								<label class="layui-form-label" style="width: 350px;">支持pdf、excel、word、图片资料，可上传多个</label>
							</div>
							<div class="layui-form-item">
							    <label class="layui-form-label width200">文件资料（选填）</label>
							    <div class="layui-input-block">
							    	<div class="layui-upload">
							    		<button type="button" class="layui-btn" id="1-upload-more">上传</button>
				                		<div class="layui-upload-list" id="1-upload-more-list">
				                		</div>
						            </div>
							    </div>
						  	</div>
					  	</div>
				  	</fieldset>
					<div class="layui-form-item" style="position: fixed ! important; right: 30px; bottom: 45%; z-index: 10000;">
						<div class="layui-input-block">
							<button class="layui-btn layui-bg-blue layui-btn-normal layui-btn-lg  layui-btn-radius" type="button" lay-submit lay-filter="addInfo_form_submit" id="addInfo_form_submit">
								<i class="layui-icon layui-icon-ok layuiadmin-button-btn"></i>
								提交
							</button>
						</div>
					</div>
				</form>
			</div>
		</div>
	</div>
	<script>
	//静态资源路径前缀
	var staticPath = '${fileHttpPre}';
	var stateJSON = <infopub:dicJson groupNo="A00010028" />;
	//管控月第一天
	var firstDay = '';
	//管控月最后一天
    var lastDay = '';
    //总节点数
    var totalMiles;
    //管控月节点数
    var monthMiles;

    layui.config({
        base: '${ctx}/resources/layuiadmin/' //静态资源所在路径
    }).extend({
            index: 'lib/index' //主入口模块
        }).use(['index', 'set', 'upload', 'element', 'laydate'],function () {
                var $ = layui.$
                ,form = layui.form
                ,element = layui.element
                ,laydate = layui.laydate
                ,upload = layui.upload;
                
                laydate.render({
            	      elem: '#query-input-month'
            	      ,type: 'month'
            	      ,done: function(value, date){
            	    	 firstDay = getCurrentMonthFirst(value);
            	    	 lastDay = getCurrentMonthLast(value);
            	    	 getMilesCount();
            	    	 calcRate();
            	      }
                })

                // 正则校验
                form.verify({
                    //验证汉字
                    CHS: [/^[\u0391-\uFFE5]+$/, '只能输入汉字'],
                    //大于0的正整数
                    intNumber: [/^[1-9]\d*$/, '请输入正确的数字'],
                    //数字只能有两位小数
                    floatNumber: [
                        /^([-]?)([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/,
                        '请输入正确的数字'],
                    //数字大于0，并只能有两位小数
                    floatAmount: [
                        /^([1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
                        //var pattern=/^((\d+\.\d*[1-9]\d{1})|(\d*[1-9]\d*\.\d{2}))$/;
                        , '请输入正确的数字']
                });
				
                var uploadRender = function(id) {
                    upload.render({
                            elem : '#' + id + '-upload-more',
                            url : basePath + '/monthCtrl/uploadAtt/',
                            multiple : true,
                            accept : 'file',
                            acceptMime : 'application/zip,application/x-rar-compressed,image/jpeg,image/png,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/pdf',
                            before : function(obj) {
                                layer.load();
                            },
                            done : function(res) {
                                if (res.code > 0) {
                                    layer.closeAll('loading');
                                    return layer.msg(res.msg, {
                                        icon : 7
                                    });
                                }
                                if (res.entity != null
                                    && res.entity.length > 0) {
                                    for ( var i in res.entity) {
                                        var preProject = res.entity[i];
                                        var arr = preProject.split("|");
                                        var imgSrc = "";
                                        var suffix = arr[0].substring(arr[0].lastIndexOf(".") + 1,arr[0].length);
                                        if (suffix == 'jpg'|| suffix == 'png') {
                                            imgSrc = "${fileHttpPre}/"+ arr[2];
                                        } else {
                                            imgSrc = "${ctx}/resources/images/"+ suffix+ ".jpg";
                                        }
                                        $('#'+ id + '-upload-more-list').append('<div class="layui-upload-img-div" id="upload_img_'+arr[1]+'"><img src="'+imgSrc+'" title="'+ arr[0] +'" class="layui-upload-img"><div class="mask"><a href="javascript:void(0)" onclick="showImg(\''+ "${fileHttpPre}"+ arr[2] + '\');">查看</a><a href="javascript:void(0)" onclick="del(\''+ arr[1]+ '\')";>删除</a></div><p>'+ arr[0] + '</p><input type="hidden" value="'+preProject+'" id="fileAtt_'+arr[1]+'" name="fileAtt" ></input></div>');
                                    }
                                }
                            },
                            allDone : function(obj) {
                                layer.closeAll('loading');
                            },
                            error : function() {
                                layer.closeAll('loading');
                                layer.msg("上传失败，请稍后再试~", {
                                    icon : 7
                                });
                            }
                        });
                }
                uploadRender(1);

                //项目名称select监听
                form.on('select(add_select_proId)', function (data) {
                    var id = data.value;
                    $('#sumPlanRate').val('');
                    $('#monthPlanRate').val('');
                    $('#delayDaysMax').val('');
                    $('#sgCityName').val('');
                    $('#query-input-month').val('');
                    $('#packPayRateId').val('');                  
                    $("#mydiv").html('');
                    $('#subDiv').html('');
                    form.render();
                    if(id==''||id==null){
                    	layer.msg('请选择项目名称',{icon: 0});
			    		return;
                    }else{
                    	getInfoByPlanId(id);
                    }  
                });
                
                //监听所有完成情况select
                form.on('select', function(data){
                	if(data.elem.name == 'finishFlag'){
	                	if(data.value == ''){
	                		return;
	                	}
	                	//判断管控月是否已经选择
	                	var ctrlMonth = $('#query-input-month').val();
	                	if(ctrlMonth == ''){
	                		return;
	                	}
                		calcRate();
                	}
               	});

                //监听提交
                form.on('submit(addInfo_form_submit)',function (data) {
                        $("#addInfo_form_submit").removeAttr("lay-submit").removeClass("layui-bg-blue").addClass("layui-btn-disabled");
                        layer.load();
                        //提交 Ajax 成功后，静态更新表格中的数据
                        $.ajax({
                            type: 'post',
                            url: basePath + '/monthCtrl/save',
                            data: $('#addInfo_form').serialize(),
                            success: function (result) {
                                if (result.success) {
                                    layer.closeAll('loading'); //关闭loading
                                    layer.msg('提交单据成功~',{icon: 1});
                                    //两秒后关闭当前页面
                                    setTimeout(function () {
                                            /**
                                             * 查找父菜单，并刷新
                                             */
                                            var topDoc = $(window.top.document);
                                            var path = basePath + '/monthCtrl/list';
                                            // 获取页面名称
                                            var name = topDoc.find(".layui-nav-item [lay-href^='"+ path + "']").text();
                                            if (name == '' || name == null) {
                                                name = '投建月度管控';
                                            }
                                            window.parent.layui.index.openTabsPage(path,name);
                                            var iframe = window.parent.layui.admin.tabsBody(window.parent.layui.admin.tabsPage.index).find(".layadmin-iframe");
                                            iframe[0].contentWindow.location.reload(true);

                                            /**
                                             * 关闭当前页
                                             */
                                            var currPath = basePath + '/monthCtrl/add';
                                            var layid = topDoc.find("li[lay-id^='"+ currPath + "']").attr('lay-id');
                                            window.parent.layui.element.tabDelete('layadmin-layout-tabs',layid);//关闭当前页
                                        },2000);
                                } else {
                                    layer.closeAll('loading'); //关闭loading
                                    $("#addInfo_form_submit").removeClass("layui-btn-disabled").addClass("layui-bg-blue").attr("lay-submit","");
                                    layer.msg(result.msg,{icon: 7});
                                }
                            },
                            error: function(result){
                            	 layer.closeAll('loading'); //关闭loading
                                 $("#addInfo_form_submit").removeClass("layui-btn-disabled").addClass("layui-bg-blue").attr("lay-submit","");
                                 layer.msg(result.msg,{icon: 7});
                            }
                        });
                    });
                // data-type事件
                $('.layui-btn.layuiadmin-btn-admin').on('click',function () {
                        var type = $(this).data('type');
                        active[type] ? active[type].call(this): '';
                    });
            });

    //删除文件
    function del(index) {
        layui.$("#fileAtt_" + index).remove();
        layui.$("#upload_img_" + index).remove();
    }

    //根据url查看文件
    function showImg(url) {
        var openWin = window.open(url,'','left=410,height=768, width=1024, top=200,  toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');
    }

    function getInfoByPlanId(planId) {
        var $ = layui.$, form = layui.form
        totalMiles = 0;
        monthMiles = 0;
        //获取项目其他信息
        $.ajax({
            type: "POST", //提交方式
            url: "${ctx}/monthCtrl/getInfoByProgramPlanId",//路径
            data: {
                "id": planId
            },//数据，这里使用的是Json格式进行传输
            success: function (result) {//返回数据根据结果进行相应的处理
                if (result.flag == true) {
                	$('#sgCityId').val(result.sgCityId);
                	$('#sgCityName').val(result.sgCityName);
                	$('#proCode').val(result.proCode);
                	$('#proName').val(result.proName);
                	$('#types').val(result.types);
                	//项目子项页面拼接
					$('#subDiv').html('');
					layui.$.each(result.subpackCots, function(i,item){
						var ind = i + 1;
						var medalHtml = '';
						medalHtml += '<div id="commRow'+ind+'">';
						medalHtml += '	<div class="layui-form-item">';
						medalHtml += '	<div class="layui-inline width106">';
						medalHtml += '		<p class="right">序号<label>'+ind+'</label>：</p>';
						medalHtml += '	</div>';
						medalHtml += '	<div class="layui-inline">';
						medalHtml += '		<label class="layui-form-label width98">分包合同名称</label>';
						medalHtml += '		<div class="layui-input-inline">';
						medalHtml += '			<input type="text" name="cotName" value="'+item.subpackCotName+'" readonly="readonly" style="border:0px" class="layui-input">';
						medalHtml += '		</div>';
						medalHtml += '	</div>';
						medalHtml += '	<div class="layui-inline">';
						medalHtml += '		<label class="layui-form-label width60">单位名称</label>';
						medalHtml += '		<div class="layui-input-inline">';
						medalHtml += '			<input type="text" name="orgName" value="'+item.sgCoopName+'" readonly="readonly" style="border:0px" class="layui-input">';
						medalHtml += '		</div>';
						medalHtml += '	</div>';
						medalHtml += '	<div class="layui-inline">';
						medalHtml += '		<label class="layui-form-label width140">分包付款完成率（%）</label>';
						medalHtml += '		<div class="layui-input-inline">';
						medalHtml += '			<input type="text" name="subpackPayRate" maxlength="6" lay-verify="required|floatNumber" class="layui-input">';
						medalHtml += '		</div>';
						medalHtml += '	</div>';
						medalHtml += '	</div>';
						medalHtml += '</div>';
						$('#subDiv').append(medalHtml);
					});
					form.render();
                    var planSubList = result.programPlanSubVos;
                    $("#mydiv").html('');
                    layui.$.each(planSubList ,function (i, item){
                    	var  tableTemplate = [];
         				tableTemplate.push('<div class="layui-form-item">');
         				tableTemplate.push('<div class="layui-inline">');
         				tableTemplate.push('<label class="layui-form-label">子项名称</label>');
         				tableTemplate.push('<input type="hidden" value="' + item.id + '" name="subId" />');
         				tableTemplate.push('<input type="hidden" value="' + item.subOrderIdx + '" name="subOrderIdx" />');
         				tableTemplate.push('<div class="layui-input-inline">');
         				tableTemplate.push('<input type="text" name="subName" value="'+item.subName+ '" style="border: 0px;" readonly="readonly" class="layui-input">');
         				tableTemplate.push('</div>');
         				tableTemplate.push('</div>');
         				tableTemplate.push('</div>');
         				tableTemplate.push('<div class="layui-form-item"  style="margin:0 20px;">');
                        tableTemplate.push('<table class="layui-table">');
                        tableTemplate.push('<thead>');
                        tableTemplate.push('<tr>');
                        tableTemplate.push('<th style="width:5%">序号</th>');
                        tableTemplate.push('<th>节点等级</th>');
                        tableTemplate.push('<th>工作节点</th>');
                        tableTemplate.push('<th>单体/分区说明</th>');
                        tableTemplate.push('<th>计划开始日期</th>');
                        tableTemplate.push('<th>计划完成日期</th>');
                        tableTemplate.push('<th>实际完成日期</th>');
                        tableTemplate.push('<th>延误天数</th>');
                        tableTemplate.push('<th>完成情况</th>');
                        tableTemplate.push('</tr>');
                        tableTemplate.push('</thead>');
                        tableTemplate.push('<tbody id="'+item.id+'">');	
                        var planMileList = item.programPlanMileList;
                        //计算总节点数
                        totalMiles = totalMiles + planMileList.length;
                        layui.$.each(planMileList ,function (index, mileItem){
                        	var levelIdxName = mileItem.levelIdx == 1 ? '里程碑节点':'管控节点';
                        	var planStartTime = layui.util.toDateString(mileItem.planStartTime,"yyyy-MM-dd");
                        	var planFinishTime = layui.util.toDateString(mileItem.planFinishTime,"yyyy-MM-dd");
                        	//计算管控节点数
                        	if(firstDay != '' && lastDay != ''){
                        		//判断计划完成日期是否在管控月内
                        		if(isDateBetween(planFinishTime,firstDay,lastDay)){
                        			monthMiles = monthMiles + 1;
                        		}
                        	}
                        	tableTemplate.push('<tr>');
                        	tableTemplate.push('<td><label><input type="text" value="'+mileItem.showOrderIdx+'" name="showOrderIdx" style="border: 0px;" readonly="readonly" class="layui-input" /></label><input type="hidden" value="'+item.subName+'" name="ctrlSubId" /></td>');
                            tableTemplate.push('<td><input type="text" value="' + levelIdxName + '" style="border: 0px;" readonly="readonly" class="layui-input" /><input type="hidden" value="' + mileItem.levelIdx + '" name="levelIdx" /></td>');
                            tableTemplate.push('<td><input type="text" value="' + mileItem.mileName + '" name="pointName" style="border: 0px;" readonly="readonly" class="layui-input" /></td>');
                            tableTemplate.push('<td><input type="text" value="' + mileItem.memo + '" name="memo" style="border: 0px;" readonly="readonly" class="layui-input"  /></td>');
                            tableTemplate.push('<td><input type="text" value="' + planStartTime + '" name="planStartTime" style="border: 0px;" readonly="readonly" class="layui-input"  /></td>');
                            tableTemplate.push('<td><input type="text" value="' + planFinishTime + '" name="planFinishTime" style="border: 0px;" readonly="readonly" class="layui-input"  /></td>');
                            tableTemplate.push('<td><input type="text" name="actFinishTime" autocomplete="off" class="layui-input sub-date" /></td>');
                            tableTemplate.push('<td><input type="text" name="delayDays" value="' + mileItem.delayDays + '" style="border: 0px;" readonly="readonly" class="layui-input" /></td>');
                            tableTemplate.push('<td><select name="finishFlag" lay-verify="required"><option value="">请选择</option><option value="0">未完成</option><option value="1">已完成</option></select></td>');
                            tableTemplate.push('</tr>');
                           // $table.append(html.join(''));                         
                        });
                        tableTemplate.push('</tbody>');	
                        tableTemplate.push('</table>');	
                        tableTemplate.push('</div>');
                        var $div = $("#mydiv");
                        $div.append(tableTemplate.join(''));
                    	
                    });
                    form.render();
                    var laydate = layui.laydate;
                    lay('.sub-date').each(function () {
                        laydate.render({
                            elem: this,
                            trigger: 'click',
                            format: 'yyyy-MM-dd',
                            done: function(value, date){
                            	if(value == ''){
                            		value = getNowFormatDate();
                            	}
                            	var planFinishTime = $(this.elem).parent().parent().find("input[name=planFinishTime]").val();
                            	var delayDays = getNumberOfDays(planFinishTime,value);
                            	if(delayDays <= 0){
                            		delayDays = 0
                            	}
                            	$(this.elem).parent().parent().find("input[name=delayDays]").val(delayDays);
                            	getMaxDelayDays();
                            }
                        });
                    });
                    getMaxDelayDays();
                } else {
                    layer.msg('数据通信异常~', {
                        icon: 0
                    });
                }
            }
        });
    }
    
    //获取当前月份的第一天
    function getCurrentMonthFirst(selectDate){
        var date = new Date(selectDate);
        date.setDate(1);
        var month = parseInt(date.getMonth()+1);
        var day = date.getDate();
        month = month < 10 ? "0"+month : month;
        day = day < 10 ? "0"+day : day;
        return date.getFullYear() + '-' + month + '-' + day;
    }
    
    /** 
     * 日期比较大小 
     * compareDateString大于dateString，返回1； 
     * 等于返回0； 
     * compareDateString小于dateString，返回-1 
     * @param dateString 日期 
     * @param compareDateString 比较的日期 
     */  
    function dateCompare(dateString, compareDateString){  
        var dateTime = new Date(dateString).getTime();  
        var compareDateTime = new Date(compareDateString).getTime();  
        if(compareDateTime > dateTime){
            return 1;  
        }else if(compareDateTime == dateTime){
            return 0;
        }else{
            return -1;  
        }
    };
    
    /** 
     * 判断日期是否在区间内，在区间内返回true，否返回false 
     * @param dateString 日期字符串 
     * @param startDateString 区间开始日期字符串 
     * @param endDateString 区间结束日期字符串 
     * @returns {Number} 
     */  
    function isDateBetween(dateString, startDateString, endDateString){  
        var flag = false;  
        var startFlag = (dateCompare(dateString, startDateString) < 1);  
        var endFlag = (dateCompare(dateString, endDateString) > -1);  
        if(startFlag && endFlag){  
            flag = true;  
        }  
        return flag;  
    }; 

    //获取当前日期
    function getNowFormatDate() {
        var date = new Date();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        month = month < 10 ? "0"+month : month;
        day = day < 10 ? "0"+day : day;
        return date.getFullYear() + "-" + month + "-" + day;
    }
    //获取当前月的最后一天
    function getCurrentMonthLast(selectDate){
        var date = new Date(selectDate);
        var currentMonth = date.getMonth();
        var nextMonth = ++currentMonth;
        var nextMonthFirstDay = new Date(date.getFullYear(),nextMonth,1);
        var oneDay = 1000*60*60*24;
        var lastTime = new Date(nextMonthFirstDay - oneDay);
        var month = parseInt(lastTime.getMonth() + 1);
        var day = lastTime.getDate();
        month = month < 10 ? "0"+month : month;
        day = day < 10 ? "0"+day : day;
        return date.getFullYear() + '-' + month + '-' + day;
    }
    
  	//获得最大的延误天数
    function getMaxDelayDays(){
  		var $ = layui.$;
  		var maxDays = 0;
  		$("input[name=delayDays]").each(function(){
  			var days = parseInt($(this).val());
  			if(days > maxDays){
  				maxDays = days;
		  	}
		});
  		$('#delayDaysMax').val(maxDays);
    };
    
  	//两个日期相减获得天数
    function getNumberOfDays(date1,date2){
        //date1：开始日期，date2结束日期
        var a1 = Date.parse(new Date(date1));
        var a2 = Date.parse(new Date(date2));
        var day = parseInt((a2-a1)/ (1000 * 60 * 60 * 24));//核心：时间戳相减，然后除以天数
        return day
    };
    
  	//获得总节点数和管控节点数
    function getMilesCount(){
  		var $ = layui.$;
  		totalMiles = $("input[name=planFinishTime]").length;
  		//计算管控节点数
    	if(firstDay != '' && lastDay != ''){
    		monthMiles = 0;
	  		$("input[name=planFinishTime]").each(function(){
	  			if($(this).val() != ''){
		  			//判断计划完成日期是否在管控月内
		    		if(isDateBetween($(this).val(),firstDay,lastDay)){
		    			monthMiles = monthMiles + 1;
		    		}
	  			}
			});
    	}
    };
    
  	//计算本月工程计划完成率和开累计划完成率
    function calcRate(){
  		var $ = layui.$;
  		//计算管控节点数
    	if(firstDay != '' && lastDay != ''){
	  		//所有已完成节点数
	  	    var totalFinishMiles = 0;
	  	    //管控月内完成节点数
	  	    var monthFinishMiles = 0;
	  		$("select[name=finishFlag]").each(function(){
	  			if($(this).val() != ''){
	  				totalFinishMiles = totalFinishMiles + parseInt($(this).val());
	  				//判断计划完成日期是否在管控月内
		    		if(isDateBetween($(this).parent().parent().find("input[name=planFinishTime]").val(),firstDay,lastDay)){
		    			monthFinishMiles = monthFinishMiles + parseInt($(this).val());
		    		}
	  			}
			});
	  		if(totalFinishMiles == 0 || totalMiles == 0){
	  			$('#sumPlanRate').val(0);
	  		}
	  		if(monthFinishMiles == 0 || monthMiles == 0){
	  			$('#monthPlanRate').val(0);
	  		}
	  		if(totalFinishMiles > 0 && totalMiles > 0){
	  			var sumPlanRate = (totalFinishMiles/totalMiles*100).toFixed(2);
	  			$('#sumPlanRate').val(sumPlanRate);
	  		}
	  		if(monthFinishMiles > 0 && monthMiles > 0){
	  			var monthPlanRate = (monthFinishMiles/monthMiles*100).toFixed(2);
	  			$('#monthPlanRate').val(monthPlanRate);
	  		}
    	}
    };
</script>
</body>
</html>